import com.acxy.ants.common.enums.TxLevel;
import com.acxy.ants.core.plugin.db.DruidPlugin;
import com.acxy.ants.core.plugin.db.Db;

import javax.sql.DataSource;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-09-08
 */
public class MyThread implements Runnable {

    public static int count = 100;

    public final static long time = System.currentTimeMillis();

    public static long time2 = System.currentTimeMillis();

    private int i = 0;
    private Db db;
    private DataSource dataSource;

    public MyThread(int i){
        this.i = i;
        DruidPlugin druidPlugin = new DruidPlugin("jdbc:mysql://127.0.0.1:3306/ants-cms?characterEncoding=utf8&tinyInt1isBit=false"
                , "com.mysql.jdbc.Driver"
                , "root"
                , "root");
        druidPlugin.start();
        this.dataSource = druidPlugin.getDataSource();
        this.db = new Db(dataSource);
    }

    @Override
    public void run() {
        while (true){
            time2 = System.currentTimeMillis();
            MyThread.count--;
            System.out.println(MyThread.count--);
            doing();
            if(MyThread.count <= 0){
                System.out.println("10 个人 并发 1000 次 执行结束....耗时" + (System.currentTimeMillis() - time) + "ms秒");
                System.exit(0);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void doing(){
        try {

            db.startTx(dataSource, "druid", TxLevel.REPEATED_READ);
            new User(35L).delete(db);
            new User(36L).delete(db);
            new User(1L).delete(db);
            db.commit();
        } catch (Exception e){
            e.printStackTrace();
            db.rollback();
        }
        System.out.println("当前模拟用户 ["+i+"] 执行完成...耗时" + (System.currentTimeMillis() - time2) + "ms秒 -> ");
    }
}
